/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mx.itesm.twritter.server.parser;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import mx.itesm.twritter.server.ontology.TwitterCalls;

/**
 *
 * @author marthahernandez
 */
public class ParsedTweet {
    private int velocity;
    private String velocityText;
    private String route;
    private String from;
    private String to;
    private String alternative;
    private String id;
    private String createdAt;
    public static final int TRAFFIC = 1;//id to indicate traffic tweets
    public static final int NOTRAFFIC = 0;
    public static ParsedTweetRegex tweetObjRegex;
    public static int tipo;
    
    public ParsedTweet(int vel, String velT, String route, String from, String to, String alternativa, String id, String createdAt){
        this.velocity = vel;
        this.velocityText = velT;
        this.route = route;
        this.from = from;
        this.to = to;
        this.alternative = alternativa;
        this.id = id;
        this.createdAt = createdAt;
    }
    
    public ParsedTweet(int vel, String velT, String route, String from, String to, String id, String createdAt){
        this.velocity = vel;
        this.velocityText = velT;
        this.route = route;
        this.from = from;
        this.to = to;
        this.alternative = null;
        this.id = id;
        this.createdAt = createdAt;
    }
    
    public ParsedTweet() {}
    
    /**
     * Creates a parsed tweet object from the given String 
     * @param tweet String that contains all the tweet text
     * @return ParsedTweet object
     */
    public static ParsedTweet createParsedTweet(String tweet, String id, String date){
    	tweetObjRegex = new ParsedTweetRegex(tweet, id.toString());
        int vel; 
        String velT, frm, t, in, alt;
        ParsedTweet tweetObj = new ParsedTweet();
        
        velT = Parser889.getRoadFromTweet(tweet,"","en");
        vel = Parser889.wordsIntoVelocity(velT);
        in = Parser889.getRoadFromTweet(tweet,"en","desde");
        frm = Parser889.getRoadFromTweet(tweet,"desde","hasta");
        t = Parser889.getRoadFromTweet(tweet, "hasta", "");
        alt = Parser889.findAlternativa(tweet);
        
        if(!velT.equals("") && !in.equals("") && !frm.equals("") && !t.equals("")){
            velT = Parser889.purgeTweet(velT);
            in = Parser889.purgeTweet(in);
            frm = Parser889.purgeTweet(frm);
            t = Parser889.purgeTweet(t);
            alt = (alt == null ? null : Parser889.purgeTweet(alt));
        } 
        
        if(in.equals("")){
            in = Parser889.findRouteInVelText(velT,NOTRAFFIC);
            velT = Parser889.findRouteInVelText(velT,TRAFFIC);
        }
        
        if(velT.equals("")){
            velT = Parser889.findVelTextInRoute(in,TRAFFIC);
            in = Parser889.findVelTextInRoute(in,NOTRAFFIC);
            vel = Parser889.wordsIntoVelocity(velT);
        }       
        
        t = removeEndChars(t);
        
        if(velT.equals("") || in.equals("") || frm.equals("") || t.equals(""))
            return null;
            
        if(alt == null)
        	if (tipo == 0)
        		tweetObj = new ParsedTweet(vel,velT,in,frm,t,id,date);
        	else if (tipo == 1) {
        		tweetObj = new ParsedTweet(vel,tweetObjRegex.getStreetVelString(),
        							tweetObjRegex.getStreetName(),
        							tweetObjRegex.getStreetFrom(),
        							tweetObjRegex.getStreetTo(),id,date);
        		
        	}
        else 
        	if (tipo == 0)
        		tweetObj = new ParsedTweet(vel,velT,in,frm,t,alt,id,date);
        	else if (tipo == 1) {
        		tweetObj = new ParsedTweet(vel,tweetObjRegex.getStreetVelString(),
					tweetObjRegex.getStreetName(),
					tweetObjRegex.getStreetFrom(),
					tweetObjRegex.getStreetTo(),
					alt, id,date);
        	}
        
        return tweetObj;
    
    }

    public String getAlternativa() {
        return alternative;
    }

    public void setAlternativa(String alternativa) {
        this.alternative = alternativa;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getRoute() {
        return route;
    }

    public void setRoute(String route) {
        this.route = route;
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public int getVelocity() {
        return velocity;
    }

    public void setVelocity(int velocity) {
        this.velocity = velocity;
    }

    public String getVelocityText() {
        return velocityText;
    }

    public void setVelocityText(String velocityText) {
        this.velocityText = velocityText;
    }
    
    @Override
    public String toString(){
        String tweet = 
                "Vel Text: " + this.velocityText + "\n"+
                "Velocity: " + this.velocity + " km/h\n" + 
                "In route: " + this.route + "\n" +
                "From: " + this.from + "\n" +
                "To: " + this.to + "\n" +
                "Alternative: " + (this.alternative == null ? "none" : this.alternative) + "\n"+
                "-----------------------------------------------";
        return tweet;
        
    }
    
    public static ArrayList<ParsedTweet> parseTweetsFromUser(String user){
    	String tweet;
        List<winterwell.jtwitter.Status> tweets = TwitterCalls.getTimelineFromUser(user);
        Iterator<winterwell.jtwitter.Status> it = tweets.iterator();
        ArrayList<ParsedTweet> parsedTweets = new ArrayList<ParsedTweet>();
        try {

            BufferedWriter out = new BufferedWriter(new FileWriter("tweets.txt", true));
            
            while (it.hasNext()) {
                winterwell.jtwitter.Status twt = (winterwell.jtwitter.Status) it.next();
                if (twt.inReplyToStatusId == null) {
                    tweet = twt.toString();
                    tweetObjRegex = new ParsedTweetRegex(tweet, twt.id.toString());
                    if (Parser889.isTrafficTweet(tweet)) {
                        ParsedTweet tweetObj = ParsedTweet.createParsedTweet(tweet,twt.id.toString(),twt.createdAt.toString());
                        //System.out.println(tweet);
                        //System.out.println(tweetObj);
                        if(tweetObj != null){
                            out.write(twt.id.toString()+"\n");
                            out.write(tweet+"\n");
                            out.write(twt.createdAt+"\n");
                            out.write(tweetObj.toString()+"\n");
                            parsedTweets.add(tweetObj);
                        }
                   }
                }
            }
            out.close();
            return parsedTweets;
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
            return null;
        } 
    }

	public void setId(String id) {
		this.id = id;
	}

	public String getId() {
		return id;
	}

	public void setCreatedAt(String createdAt) {
		this.createdAt = createdAt;
	}

	public String getCreatedAt() {
		return createdAt;
	}
	
	public static String removeEndChars(String tweet){
		String[] splitTweet = tweet.split("\\.");
		String res = "";
		String last = splitTweet[splitTweet.length-1].trim();
		if(last.length() < 4){
			for(int i=0; i<splitTweet.length-1;i++){
				res += splitTweet[i];
			}
		}else{
			res = tweet;
		}	
		return res.trim();
	}
   
}
